package com.david;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * 具体的业务逻辑
 * @Component 单例对象，线程不安全
 */
@Component
public class FluxHandler {

    /**
     * 简单值返回
     * @param request
     * @return
     */
    public Mono<ServerResponse> getXXX(ServerRequest request){
        //业务逻辑
        return ServerResponse
                .ok()
                .contentType(MediaType.TEXT_PLAIN)//返回的数据类型
                .body(BodyInserters.fromValue("memeda"));
    }


    /**
     * 返回json
     * @param request
     * @return
     */
    public Mono<ServerResponse> getJsonXXX(ServerRequest request){

        //对象
        Person person = new Person();
        person.setId(1);
        person.setName("小王同学");

        //业务逻辑
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)//返回的数据类型
                .body(BodyInserters.fromValue(person));
    }

    /**
     * 传参数
     * @param request
     * @return
     */
    public Mono<ServerResponse> getParams(ServerRequest request){

        Optional<String> id = request.queryParam("id");

        MultiValueMap<String, String> queryParams = request.queryParams();

        System.out.println("id"+id);
        System.out.println("queryParams"+queryParams);

        //业务逻辑
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)//返回的数据类型
                .body(BodyInserters.fromValue("ok"));
    }

    /**
     * path 取值
     * @param request
     * @return
     */
    public Mono<ServerResponse> getPath(ServerRequest request){

        String id = request.pathVariable("id");
        String name = request.pathVariable("name");
        System.out.println("id"+id);
        System.out.println("name"+name);

        //业务逻辑1
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)//返回的数据类型
                .body(BodyInserters.fromValue("ok"));

        //业务逻辑2
//        return ServerResponse.status(666).build();

        //业务逻辑3
//        return ServerResponse.status(404).contentType(MediaType.TEXT_HTML)
//                .body(BodyInserters.fromValue("find nothing"));


    }










}
